from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
from io import BytesIO
from datetime import datetime
import uuid

# os.environ['PYTORCH_ENABLE_MPS_FALLBACK'] = '1'  # 确保直接启动推理UI时也能够设置。
# 1. 设置用户属性, 包括 secret_id, secret_key, region等。Appid 已在 CosConfig 中移除，请在参数 Bucket 中带上 Appid。Bucket 由 BucketName-Appid 组成
secret_id = "AKID6CeQB7DPezIguBX9gBWgtuv4DHNMF4lR"     # 用户的 SecretId，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
secret_key = "29C9xgXPHCAwhWIuPCFUrFoXH8xNTi4Y"   # 用户的 SecretKey，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
region = 'ap-shanghai'      # 替换为用户的 region，已创建桶归属的 region 可以在控制台查看，https://console.cloud.tencent.com/cos5/bucket
                           # COS 支持的所有 region 列表参见 https://cloud.tencent.com/document/product/436/6224
token = None               # 如果使用永久密钥不需要填入 token，如果使用临时密钥需要填入，临时密钥生成和使用指引参见 https://cloud.tencent.com/document/product/436/14048
scheme = 'https'           # 指定使用 http/https 协议来访问 COS，默认为 https，可不填
domain = "https://digivio-tts-1323248546.cos.ap-shanghai.myqcloud.com"
cosconfig = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token,Scheme=scheme)
client = CosS3Client(cosconfig)

def upload2oss(name,imagedata):    
    current = datetime.now()
    path = "/".join([str(current.year),str(current.month),str(current.day),str(current.hour)])
    upname = path+"/" + name
    
    url = "https://digivio-tts-1323248546.cos.ap-shanghai.myqcloud.com/" + upname

    with BytesIO() as imageContent:
            # wavfile.write(wavContent, sr, wav)
            imagedata.save(imageContent, format='PNG')
            response = client.put_object(
                    Bucket='digivio-tts-1323248546',
                    Body=imageContent.getvalue(),
                    Key=upname,
                    EnableMD5=False
            )            
            return url
    return None